package cn.yunhe.action;

import cn.yunhe.entity.House;
import cn.yunhe.entity.Location;
import cn.yunhe.entity.Type;
import cn.yunhe.entity.User;
import cn.yunhe.server.HouseDaoServer;
import cn.yunhe.server.LocationDaoServer;
import cn.yunhe.server.TypeDaoServer;
import cn.yunhe.util.ActionUtil;
import cn.yunhe.util.PageUtil;
import com.opensymphony.xwork2.ModelDriven;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HouseAction extends ActionUtil {
    private House house;
    private Type type;
    private Location location;
    private File upload; //定义上传的文件
    private String uploadContentType; //定义文件属性
    private String uploadFileName; //定义文件名
    private String path; //定义文件存储的路径
    private String price; //定义房屋价格字符串
    private String area; //定义房屋面积字符串
    private int currPage; //返回当前页码
    private List<House> houseList = new ArrayList<House>(); //房屋对象集合
    private Map<String, Object> map = new HashMap<String, Object>();
    private String keyword;

    /**
     * 房屋信息发布方法
     *
     * @return
     */
    public String issueHouseInfo() {
        //获取server层对象
        HouseDaoServer houseDaoServer = new HouseDaoServer(); //房子信息管理server
        TypeDaoServer typeDaoServer = new TypeDaoServer(); //房子类型信息管理server
        LocationDaoServer locationDaoServer = new LocationDaoServer(); //地址信息管理server

        Map request = getMapRequest(); //获取request对象

        Map session = getMapSession(); //获取session对象
        User user = (User) session.get("user"); //从session中获取用户对象
        if (user == null) {
            return LOGIN;
        } else {
            Type type1 = typeDaoServer.getType(type.getTname()); //查询页面获取的类型对象在数据库中是否存在
            if (type1 == null) { //若type1对象不存在说明数据库中还没有该类型,则执行插入方法插入类型信息,否则直接使用页面的的type对象信息
                boolean flag = typeDaoServer.insertType(type);
                if (flag) { //插入成功则执行查询方法,并将新对象赋予type1引用
                    type1 = typeDaoServer.getType(type.getTname());
                } else { //插入失败则直接返回error界面
                    return ERROR;
                }
            }

            Location location1 = locationDaoServer.getLocation(location);
            if (location1 == null) { //若location1对象不存在说明数据库中还没有该地址信息,则执行插入方法插入地址信息,否则直接使用页面的的location对象信息
                boolean flag = locationDaoServer.insertLocation(location);
                if (flag) { //插入成功则执行查询方法,并将新对象赋予location1引用
                    location1 = locationDaoServer.getLocation(location);
                } else { //插入失败则直接返回error界面
                    return ERROR;
                }
            }

            //将用户对象,地址对象,类型对象,图片名赋予house对象
            house.setUser(user);
            house.setLocation(location1);
            house.setType(type1);
            house.setPic(uploadFileName);
            String newPath = getPath() + "\\" + getUploadFileName();  //获取文件的完整路径
            doUpload(upload, newPath); //执行文件上传
            boolean fg = houseDaoServer.issueHouseInfo(house); //执行发布房屋信息方法
            if (fg) { //发布成功则提交事务,返回信息发布界面并返回结果
                request.put("result", "房屋信息发布成功!!");
                return SUCCESS;
            } else {
                request.put("result", "房屋信息发布失败!!");
                return SUCCESS;
            }
        }
    }

    /**
     * 文件上传方法
     *
     * @param file
     */
    public void doUpload(File file, String path) {
        try {
            FileInputStream fis = new FileInputStream(file); //读入文件内容
            FileOutputStream fos = new FileOutputStream(path); //向磁盘写入内容
            byte[] b = new byte[1024];
            int len = 0;
            while ((len = fis.read(b)) != -1) {
                fos.write(b, 0, len);
            }
            fis.close();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 查询所有房源信息
     *
     * @return
     */
    public String queryHouse() {
        Map<String, Object> mapResult = new HashMap<String, Object>();
        Map request = getMapRequest();

        //若传回来的数据字符串为"",说明该选择未选择,将该值赋值为空
        //若对象均为空说明是第一次跳转该页面,将相应属性赋值为空
        if (house == null) {
            mapResult.put("title", null);
        } else {
            if (house.getTitle().equals("")) {
                mapResult.put("title", null);
            } else {
                mapResult.put("title", house.getTitle());
            }
        }
        if (price == null) {
            mapResult.put("price", null);
        } else {
            if (price.equals("")) {
                mapResult.put("price", null);
            } else {
                mapResult.put("price", price);
            }
        }
        if (type == null) {
            mapResult.put("type", null);
        } else {
            if (type.getTname().equals("")) {
                mapResult.put("type", null);
            } else {
                mapResult.put("type", type.getTname());
            }
        }
        if (area == null) {
            mapResult.put("area", null);
        } else {
            if (area.equals("")) {
                mapResult.put("area", null);
            } else {
                mapResult.put("area", area);
            }
        }
        if (location == null) {
            mapResult.put("province", null);
            mapResult.put("city", null);
            mapResult.put("district", null);
        } else {
            if (location.getProvince().equals("")) {
                mapResult.put("province", null);
            } else {
                mapResult.put("province", location.getProvince());
            }

            if (location.getCity().equals("")) {
                mapResult.put("city", null);
            } else {
                mapResult.put("city", location.getCity());
            }

            if (location.getDistrict().equals("")) {
                mapResult.put("district", null);
            } else {
                mapResult.put("district", location.getDistrict());
            }
        }
        HouseDaoServer houseDaoServer = new HouseDaoServer();
        int totalRows = houseDaoServer.countRows(mapResult);
        int totalPages = PageUtil.getTotalPages(totalRows); //获取总页数
        if (currPage == 0) {  //如果当前页面为0则说明是刚加载,将该页初始化为1
            currPage = 1;
        }
        List<House> list = houseDaoServer.queryHouse(mapResult, currPage); //查询房屋,获取房屋信息集合
        if (list != null && list.size() > 0) {
            //将房屋集合和总行数及总页数存入集合
            request.put("list", list);
            request.put("totalRows", totalRows);
            request.put("totalPages", totalPages);
            return SUCCESS;
        } else {
            request.put("result", "暂无房屋信息!!");
            return SUCCESS;
        }
    }


    /**
     * 获取所有房屋信息集合
     *
     * @return
     */
    public String getAllHouse() {
        HouseDaoServer houseDaoServer = new HouseDaoServer();
        houseList = houseDaoServer.getAllHouse();
        return SUCCESS;
    }

    /**
     * 查询所有房源信息
     *
     * @return
     */
    public String getAllHouseInfo() {
        HouseDaoServer houseDaoServer = new HouseDaoServer();
        int totalRows = houseDaoServer.countAllRows(); //统计总行数
        int totalPage = PageUtil.getTotalPages(totalRows); //计算总页数
        houseList = houseDaoServer.getAllHouseInfo(currPage); //执行查询
        //将信息存入map集合中
        map.put("totalPage", totalPage);
        map.put("currPageIndex", currPage);
        map.put("houseList", houseList);
        return SUCCESS;
    }

    /**
     * 通过房屋id查询房屋信息
     *
     * @return
     */
    public String getHouseById() {
        Map request = getMapRequest();
        if (house != null) {
            int hid = house.getHid(); //获取房屋id
            HouseDaoServer houseDaoServer = new HouseDaoServer();
            House newHouse = houseDaoServer.getHouseById(hid); //通过查询获取house对象
            request.put("house", newHouse);
            return SUCCESS;
        } else {
            request.put("result", "参数传递异常<a href='javascript:history.go(-1)'>返回上一级</a>");
            return ERROR;
        }
    }

    /**
     * 模糊查询房屋信息
     *
     * @return
     */
    public String getHouseByFuzzySerch() {
        HouseDaoServer houseDaoServer = new HouseDaoServer();
        houseList = houseDaoServer.fuzzySerchHouse(keyword); //通过关键字查询房屋信息
        return SUCCESS;
    }

    /**
     * 通过搜索获取房屋信息
     *
     * @return
     */
    public String serchHouse() {
        HouseDaoServer houseDaoServer = new HouseDaoServer();
        List<House> houses = houseDaoServer.fuzzySerchHouse(house.getTitle());
        Map request = getMapRequest();
        if (houses != null && houses.size() > 0) {
            request.put("list", houses);
            return SUCCESS;
        } else {
            return ERROR;
        }
    }

    public House getHouse() {
        return house;
    }

    public void setHouse(House house) {
        this.house = house;
    }

    public Type getType() {
        return type;
    }

    public void setType(Type type) {
        this.type = type;
    }

    public Location getLocation() {
        return location;
    }

    public void setLocation(Location location) {
        this.location = location;
    }

    public File getUpload() {
        return upload;
    }

    public void setUpload(File upload) {
        this.upload = upload;
    }

    public String getUploadFileName() {
        return uploadFileName;
    }

    public void setUploadFileName(String uploadFileName) {
        this.uploadFileName = uploadFileName;
    }

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    public String getUploadContentType() {
        return uploadContentType;
    }

    public void setUploadContentType(String uploadContentType) {
        this.uploadContentType = uploadContentType;
    }

    public String getPrice() {
        return price;
    }

    public void setPrice(String price) {
        this.price = price;
    }

    public String getArea() {
        return area;
    }

    public void setArea(String area) {
        this.area = area;
    }


    public int getCurrPage() {
        return currPage;
    }

    public void setCurrPage(int currPage) {
        this.currPage = currPage;
    }

    public List<House> getHouseList() {
        return houseList;
    }

    public void setHouseList(List<House> houseList) {
        this.houseList = houseList;
    }

    public Map<String, Object> getMap() {
        return map;
    }

    public void setMap(Map<String, Object> map) {
        this.map = map;
    }

    public String getKeyword() {
        return keyword;
    }

    public void setKeyword(String keyword) {
        this.keyword = keyword;
    }
}
